package com.example.loginapp.controller;

import com.example.loginapp.service.IUserService;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping({"/user"})
public class UserController {
    @Autowired
    private IUserService userService;

    public UserController() {
    }

//    @PostMapping({"/login"})
//    public Map<String, Object> login(String userName, String password, HttpSession session) {
//
//        Map<String, Object> result = new HashMap();
//        result.put("success", false);
//        result.put("message", "错误的用户名或者密码");
//        if (this.userService.verify(userName, password)) {
//            result.put("success", true);
//            result.put("message", "");
//            session.setAttribute("user", userName);
//        }
//
//        return result;
//    }
//HttpSession中可以跟踪并储存用户信息，把值设置到属性中，有2个方法：setAttribute(),getAttrribute()；
//
//例如：在一个方法中用session.setAttribute(“student”,student);
// 在session中设置一个属性名为student,值为一个名为student的对象。
// 而后可在同一session范围内用getAttribute(“student”)取出该属性，得到student对象。
    @PostMapping({"/login"})
    public Map<String, Object> login(@RequestBody Map<String,Object> map, HttpSession session) {
        String userName = (String) map.get("userName");
        String password = (String) map.get("password");
        System.out.println(map.get("userName"));
        System.out.println(map.get("password"));
        System.out.println(map);

        Map<String, Object> result = new HashMap();
        result.put("success", false);
        result.put("message", "错误的用户名或者密码");
        if (this.userService.verify(userName, password)) {
            result.put("success", true);
            result.put("message", "登录成功");
            session.setAttribute("user",userName);
        }
        return result;
    }

    @GetMapping({"/"})
    public Map<String, Object> getAllUsers(@RequestBody HttpSession session) {
        Map<String, Object> result = new HashMap();
        if (session.getAttribute("user") == null) {
            result.put("success", false);
            result.put("message", "请先登录");
        } else {
            result.put("success", true);
            result.put("message", "");
            result.put("data", this.userService.findAll());
        }

        return result;
    }

    @PostMapping({"/logout"})
    public Map<String, Object> logout(@RequestBody HttpSession session) {
        Map<String, Object> result = new HashMap();
        result.put("success", true);
        result.put("message", "");
        session.setAttribute("user", (Object)null);
        return result;
    }
}